<template>
  <div class="attendance-result-container">
    <el-card class="main-card">
      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button @click="handleBack">
          <el-icon><Back /></el-icon>
          返回
        </el-button>
      </div>

      <!-- 搜索表单 -->
      <div class="search-header">
        <el-form :model="searchForm" inline>
          <el-form-item label="学号">
            <el-input 
              v-model="searchForm.studentId" 
              placeholder="输入学号搜索"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>

          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="全部状态"
              clearable
              style="width: 120px"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button 
              type="primary" 
              @click="handleSearch"
              :loading="loading"
            >
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
            <el-button type="success" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出结果
        </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
        empty-text="暂无签到记录"
        stripe
      >
        <el-table-column prop="studentId" label="学号" width="180" fixed />
        <el-table-column prop="name" label="姓名" width="180" />
        <el-table-column prop="status" label="状态" width="180">
          <template #default="{ row }">
            <el-tag :type="statusTagMap[row.status]">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="signTime" label="签到时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.signTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-select
              v-model="row.status"
              placeholder="修改状态"
              :loading="row.updating"
              @change="(val) => handleStatusChange(row, val)"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        class="pagination"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next"
        @size-change="handlePageChange"
        @current-change="handlePageChange"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Download, Back } from '@element-plus/icons-vue'
import axios from 'axios'
import dayjs from 'dayjs'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()
const API_BASE = 'http://localhost:8080/attendance-records'
const api = {
  list: `${API_BASE}/list`,
  update: id => `${API_BASE}/update/${id}`,
  export: `${API_BASE}/export`
}

// 状态配置（与后端保持一致）
const statusOptions = [
  { value: '已签到', label: '已签到' },
  { value: '迟到', label: '迟到' },
  { value: '未签到', label: '未签到' }
]

const statusTagMap = {
  '已签到': 'success',
  '迟到': 'warning',
  '未签到': 'danger'
}

// 响应式数据
const searchForm = reactive({
  studentId: '',
  status: ''
})

const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取会话ID
const sessionId = ref(route.params.id || 0)

// 时间格式化
const formatTime = (time) => {
  return time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : 'N/A'
}

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true
    const params = {
      currentPage: currentPage.value,
      pageSize: pageSize.value,
      id: sessionId.value,
      studentId: searchForm.studentId,
      status: searchForm.status
    }

    // 清理空参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === undefined) delete params[key]
    })

    const response = await axios.get(api.list, { params })
    const { records, total: totalCount } = response.data.data

    tableData.value = records.map(item => ({
      ...item,
      originalStatus: item.status,
      updating: false
    }))
    // console.log(tableData.value)
    total.value = totalCount
  } catch (error) {
    ElMessage.error(`数据加载失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const handleReset = () => {
  searchForm.studentId = ''
  searchForm.status = ''
  handleSearch()
}

// 分页处理
const handlePageChange = () => {
  fetchData()
}
// 返回上一页
const handleBack = () => {
  router.go(-1)
}
// 修改状态
const handleStatusChange = async (row, newStatus) => {
  try {
    row.updating = true
    console.log(row.recordId, newStatus)
    await ElMessageBox.confirm(
      `确认将【${row.name}】的状态修改为【${newStatus}】吗？`,
      '状态修改确认',
      { type: 'warning' }
    )

    const response = await axios.put(api.update(row.recordId), {
      status: newStatus
    })

    if (response.data.code === 200) {
      ElMessage.success('状态更新成功')
      row.originalStatus = newStatus
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`更新失败: ${error.response?.data?.message || error.message}`)
      row.status = row.originalStatus
    }
  } finally {
    row.updating = false
  }
}

// 导出处理
const handleExport = async () => {
  try {
    const params = {
      id: sessionId.value,
      studentId: searchForm.studentId,
      status: searchForm.status
    }

    const response = await axios.get(api.export, {
      params,
      responseType: 'blob'
    })

    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', `签到记录_${dayjs().format('YYYYMMDDHHmmss')}.xlsx`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (error) {
    ElMessage.error(`导出失败: ${error.message}`)
  }
}

// 初始化加载
onMounted(fetchData)
</script>

<style scoped>
.attendance-result-container {
  padding: 20px;
  background: #f5f7fa;
  height: 100%;
}

.main-card {
  min-height: calc(100vh - 100px);
}

.action-buttons {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.search-header {
  margin-bottom: 20px;
}

.el-form--inline .el-form-item {
  margin-right: 20px;
  margin-bottom: 10px;
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>